{% extends "base.html" %}

{% block title %}漫画列表 - 漫画阅读器{% endblock %}

{% block content %}
<div class="comic-list-container">
    <!-- 页面标题和搜索 -->
    <section class="list-header">
        <div class="header-content">
            <h1 class="page-title">漫画列表</h1>
            <div class="search-container">
                <form method="GET" action="{{ url_for('main.comic_list') }}" class="search-form">
                    <div class="search-input-group">
                        <input type="text" 
                               name="search" 
                               value="{{ search }}" 
                               placeholder="搜索漫画..." 
                               class="search-input"
                               autocomplete="off">
                        <button type="submit" class="search-btn">
                            <span class="search-icon">🔍</span>
                        </button>
                    </div>
                    {% if search %}
                    <a href="{{ url_for('main.comic_list') }}" class="clear-search">
                        <span class="clear-icon">✕</span>
                        <span class="clear-text">清除搜索</span>
                    </a>
                    {% endif %}
                </form>
            </div>
        </div>
        
        <!-- 结果统计 -->
        <div class="list-stats">
            {% if search %}
                <p class="stats-text">搜索"{{ search }}"找到 {{ pagination.total or 0 }} 个结果</p>
            {% else %}
                <p class="stats-text">共 {{ pagination.total or 0 }} 部漫画</p>
            {% endif %}
        </div>
    </section>

    <!-- 漫画网格 -->
    <section class="comics-section">
        {% if comics %}
        <div class="comics-grid">
            {% for comic in comics %}
            <div class="comic-card" data-comic-id="{{ comic.id }}">
                <a href="{{ url_for('main.comic_detail', comic_id=comic.id) }}" class="comic-link">
                    <div class="comic-cover">
                        {% if comic.cover_image %}
                            <img src="/api/thumbnail/{{ comic.cover_image | urlencode }}?width=300&height=400" 
                                 alt="{{ comic.title }}" 
                                 loading="lazy"
                                 class="cover-image"
                                 onerror="this.src='/static/images/icons/default-cover.png'">
                        {% else %}
                            <div class="cover-placeholder">
                                <span class="placeholder-icon">📖</span>
                                <span class="placeholder-text">暂无封面</span>
                            </div>
                        {% endif %}
                        
                        <div class="comic-overlay">
                            <div class="overlay-content">
                                <div class="comic-stats">
                                    <span class="stat-badge">
                                        <span class="stat-icon">📑</span>
                                        <span class="stat-text">{{ comic.total_chapters }}章</span>
                                    </span>
                                    <span class="stat-badge">
                                        <span class="stat-icon">📄</span>
                                        <span class="stat-text">{{ comic.total_pages }}页</span>
                                    </span>
                                </div>
                                
                                <div class="comic-actions">
                                    <button class="action-btn read-btn" 
                                            onclick="event.preventDefault(); startReading('{{ comic.id }}')">
                                        <span class="btn-icon">▶️</span>
                                        <span class="btn-text">开始阅读</span>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="comic-meta">
                        <h3 class="comic-title" title="{{ comic.title }}">{{ comic.title }}</h3>
                        <div class="comic-info">
                            <div class="info-row">
                                <span class="info-label">章节:</span>
                                <span class="info-value">{{ comic.total_chapters }}</span>
                            </div>
                            <div class="info-row">
                                <span class="info-label">页数:</span>
                                <span class="info-value">{{ comic.total_pages }}</span>
                            </div>
                            {% if comic.updated_at %}
                            <div class="info-row">
                                <span class="info-label">更新:</span>
                                <span class="info-value update-time" data-time="{{ comic.updated_at }}">
                                    {{ comic.updated_at }}
                                </span>
                            </div>
                            {% endif %}
                        </div>
                    </div>
                </a>
            </div>
            {% endfor %}
        </div>
        {% else %}
        <div class="empty-state">
            <div class="empty-icon">📚</div>
            <div class="empty-title">
                {% if search %}
                    没有找到匹配的漫画
                {% else %}
                    还没有漫画
                {% endif %}
            </div>
            <div class="empty-desc">
                {% if search %}
                    尝试使用其他关键词搜索，或<a href="{{ url_for('main.comic_list') }}">浏览所有漫画</a>
                {% else %}
                    请先<a href="{{ url_for('main.scan_comics') }}">扫描漫画目录</a>来添加漫画
                {% endif %}
            </div>
        </div>
        {% endif %}
    </section>

    <!-- 分页 -->
    {% if pagination and pagination.total_pages > 1 %}
    <section class="pagination-section">
        <div class="pagination">
            {% if pagination.has_prev %}
                <a href="{{ url_for('main.comic_list', page=1, search=search) }}" 
                   class="page-btn first-btn" title="首页">
                    <span class="btn-icon">⏮️</span>
                </a>
                <a href="{{ url_for('main.comic_list', page=pagination.prev_num, search=search) }}" 
                   class="page-btn prev-btn" title="上一页">
                    <span class="btn-icon">◀️</span>
                </a>
            {% endif %}
            
            <div class="page-info">
                <span class="current-page">{{ pagination.page }}</span>
                <span class="page-separator">/</span>
                <span class="total-pages">{{ pagination.total_pages }}</span>
            </div>
            
            {% if pagination.has_next %}
                <a href="{{ url_for('main.comic_list', page=pagination.next_num, search=search) }}" 
                   class="page-btn next-btn" title="下一页">
                    <span class="btn-icon">▶️</span>
                </a>
                <a href="{{ url_for('main.comic_list', page=pagination.total_pages, search=search) }}" 
                   class="page-btn last-btn" title="末页">
                    <span class="btn-icon">⏭️</span>
                </a>
            {% endif %}
        </div>
        
        <div class="pagination-info">
            <span class="info-text">
                显示第 {{ ((pagination.page - 1) * pagination.limit + 1) }} - 
                {{ (pagination.page * pagination.limit) if (pagination.page * pagination.limit) < pagination.total else pagination.total }} 
                项，共 {{ pagination.total }} 项
            </span>
        </div>
    </section>
    {% endif %}
</div>
{% endblock %}

{% block scripts %}
<script>
// 漫画列表特定脚本
document.addEventListener('DOMContentLoaded', function() {
    // 格式化更新时间
    const updateTimes = document.querySelectorAll('.update-time');
    updateTimes.forEach(function(element) {
        const timeStr = element.dataset.time;
        if (timeStr) {
            try {
                const date = new Date(timeStr);
                const now = new Date();
                const diff = now - date;
                
                if (diff < 24 * 60 * 60 * 1000) { // 一天内
                    element.textContent = '今天';
                } else if (diff < 7 * 24 * 60 * 60 * 1000) { // 一周内
                    const days = Math.floor(diff / (24 * 60 * 60 * 1000));
                    element.textContent = days + '天前';
                } else {
                    element.textContent = date.toLocaleDateString('zh-CN');
                }
            } catch (e) {
                element.textContent = '未知';
            }
        }
    });

    // 搜索框自动聚焦（仅桌面端）
    if (window.innerWidth > 768) {
        const searchInput = document.querySelector('.search-input');
        if (searchInput && !searchInput.value) {
            searchInput.focus();
        }
    }

    // 搜索框实时提示
    const searchInput = document.querySelector('.search-input');
    if (searchInput) {
        let searchTimeout;
        searchInput.addEventListener('input', function() {
            clearTimeout(searchTimeout);
            const query = this.value.trim();
            
            if (query.length >= 2) {
                searchTimeout = setTimeout(function() {
                    // 这里可以实现实时搜索提示
                    console.log('搜索提示:', query);
                }, 300);
            }
        });
    }

    // 懒加载图片
    const images = document.querySelectorAll('img[loading="lazy"]');
    if ('IntersectionObserver' in window) {
        const imageObserver = new IntersectionObserver(function(entries) {
            entries.forEach(function(entry) {
                if (entry.isIntersecting) {
                    const img = entry.target;
                    img.classList.add('loaded');
                    imageObserver.unobserve(img);
                }
            });
        });

        images.forEach(function(img) {
            imageObserver.observe(img);
        });
    }
});

// 开始阅读函数
function startReading(comicId) {
    showLoading('正在加载阅读器...');
    
    // 获取漫画信息
    fetch(`/api/comics/${comicId}`)
        .then(response => response.json())
        .then(data => {
            if (data.status === 'success' && data.data.chapters.length > 0) {
                const firstChapter = data.data.chapters[0];
                const readerUrl = `/reader/${comicId}/${firstChapter.id}/1`;
                window.location.href = readerUrl;
            } else {
                alert('该漫画暂无可阅读的章节');
                hideLoading();
            }
        })
        .catch(error => {
            console.error('获取漫画信息失败:', error);
            alert('加载失败，请稍后重试');
            hideLoading();
        });
}

// 键盘快捷键
document.addEventListener('keydown', function(e) {
    // 按 / 键聚焦搜索框
    if (e.key === '/' && !e.ctrlKey && !e.metaKey) {
        e.preventDefault();
        const searchInput = document.querySelector('.search-input');
        if (searchInput) {
            searchInput.focus();
            searchInput.select();
        }
    }
    
    // ESC 键清除搜索
    if (e.key === 'Escape') {
        const searchInput = document.querySelector('.search-input');
        if (searchInput && searchInput.value) {
            searchInput.value = '';
            searchInput.form.submit();
        }
    }
});
</script>
{% endblock %}